package com.wmlive.networklib.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * Created by lsq on 5/9/2017.
 */

public class NetUtil {
    /**
     * 获取当前网络连接类型
     *
     * @return -1.None  0.MOBILE   1.TYPE_WIFI   7.BLUETOOTH   9.ETHERNET
     */
    public static int getNetworkType(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null) {
            return networkInfo.getType();
        }
        return -1;
    }


    /**
     * 是否连接到了网络
     *
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        return getNetworkType(context) > -1;
    }

    /**
     * 是否是wifi
     *
     * @param context
     * @return
     */
    public static boolean isWifi(Context context) {
        return getNetworkType(context) == 1;
    }

    /**
     * 获取当前网络类型，
     *
     * @param context
     * @return 0：wifi    1:移动网络   2::无网络
     */
    public static int getNetworkState(Context context) {
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        //获取WIFI连接的信息
        NetworkInfo wifiNetworkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        //获取移动数据连接的信息
        NetworkInfo dataNetworkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        int result = 0;
        if ((wifiNetworkInfo == null || !wifiNetworkInfo.isConnected())) {
            if (dataNetworkInfo != null && dataNetworkInfo.isConnected()) {
//                ToastUtil.showToast("当前正在使用流量");
                result = 1;
            } else {
//                ToastUtil.showToast("当前无网络");
                result = 2;
            }
        }
        return result;
    }
}
